<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<%@ include file="/common/plateform/include/common-base.jsp"%>
	<title>ius接口选择器</title>
	<script src="${ctx}/common/plateform/plugins/monaco-editor/min/vs/loader.js"></script>
</head>

<form class="form-horizontal" role="form" id="submitForm" action="javascript:;">
	<input type="hidden" name="pageName" value="sys-param-manager"/>
	<input type="hidden" name="formName" value="addForm"/>
	<input type="hidden" id="w_infoId" name="sysParamManager.w_infoId" value=""/>
	<input type="hidden" id="formToken" name="formToken"  value="${formToken}"/>
	<input id="delStatus" name="sysParamManager.delStatus" type="hidden" value="F" />
	<input name="sysParamManager.sysName" type="hidden" value="${param.sysEname}" />
	<div class="box-body" id="submitFormData">
		<div class="panel" id="tab_1">

			<div class="panel-body">

				<div class="col-sm-12 mb15">
					<label class="col-sm-2 control-label" >增删改查接口</label>
					<div class="col-sm-8">
						<input type="text" id="submitForm_modelTypes"  class="form-control clean" name="sysParamManager.modelTypes" data-name="sysParamManager.modelTypes" placeholder="请点击右侧按钮选择接口类型"/>
					</div>
					<div class="col-sm-2">
						<button type="button" onclick="showObjNameTable()" class="btn btn-primary btn-sm"><i class="fa fa-search-plus"></i> 选择接口类型</button>
					</div>
				</div>

				<div class="col-sm-12 mb15">
					<label class="col-sm-2 control-label">pageName</label>
					<div class="col-sm-4 form-group">
						<input type="text" id="pageName" name="sysParamManager.pageName" data-name="sysParamManager.pageName" class="form-control clean" placeholder="必填项"  maxlength="30">
					</div>
					<label class="col-sm-2 control-label" >formName</label>
					<div class="col-sm-4 form-group">
						<input type="text" id="formName" name="sysParamManager.formName" data-name="sysParamManager.formName" class="form-control clean" placeholder="必填项" maxlength="30">
					</div>
				</div>


				<div class="col-sm-12 mb15 resultName" style="display: none;">
					<label class="col-sm-2 control-label" >返回类型</label>
					<div class="col-sm-10" >
						<select id="resultName" class="form-control" name="sysParamManager.resultName">
						</select>
					</div>
				</div>

				<div class="col-sm-12 mb15">
					<label class="col-sm-2 control-label" >关联关系</label>
					<div class="col-sm-10">

						<input type="hidden" id="relation"  class="form-control clean" name="sysParamManager.relation" data-name="sysParamManager.relation" rows="2" cols="50"></input>
						<input type="hidden" id="s_relation" class="form-control clean"  name="sysParamManager.s_relation" data-name="sysParamManager.relation" ></input>

						<div id="relation_editor" style="min-height:180px;" >
							<style>
								/*.margin {
                                    display: none!important;
                                }
                                .monaco-scrollable-element.editor-scrollable.vs,.monaco-scrollable-element.editor-scrollable.vs-dark{
                                    left: 0!important;
                                }
                                .view-lines >div:nth-of-type(1) span {
                                    color: red!important;
                                }*/
							</style>
							<%--<style>
                                .monaco-editor .view-overlays .current-line{
                                    height: 34px!important;
                                }
                                .monaco-editor .cursors-layer>.cursor{
                                    height: 34px!important;
                                }
                                .view-lines div{
                                    height: 34px!important;
                                }
                            </style>--%>
						</div>



					</div>
				</div>

				<div class="col-sm-12 mb15">
					<label class="col-sm-2 control-label" >返回列</label>
					<div class="col-sm-10">
						<input type="hidden" id="resultColumn" class="form-control clean" data-name="sysParamManager.resultColumn" name="sysParamManager.resultColumn"></input>
						<input type="hidden" id="s_resultColumn" class="form-control clean" data-name="sysParamManager.resultColumn" name="sysParamManager.s_resultColumn" style="display: none"></input>
						<div id="resultColumn_editor" style="min-height:180px;" ></div>


					</div>
				</div>
				<div class="col-sm-12 mb15">
					<label class="col-sm-2 control-label" >拦截方式</label>
					<div class="col-sm-10">
						<select id="evelName" class="form-control clean" name="sysParamManager.evelName">
							<option value="beforMethodKey" selected="selected">方法前拦截</option>
							<option value="afterMethodKey">方法后拦截</option>
						</select>
					</div>
				</div>
				<div class="col-sm-12 mb15">
					<label class="col-sm-2 control-label" >插件组合</label>
					<div class="col-sm-10">
						<select id="submitForm_rulesName"
								name="sysParamManager.rulesName" class="form-control clean"
								data-temp-obj="rulesName" data-name="sysParamManager.rulesName"
								data-page-name="sysPluginGroup-list"
								data-form-name="dictForm"
								data-dict-code="dymicSql" data-dict-cate=""  data-condition="sysPluginGroup.w_delStatus=F&sysPluginGroup.wi_sysName=${param.sysEname}"
								data-colmun="{value:'rulesCode',text:'rulesCode,rulesRemark',other:'rulesId'}"
								data-type-tag="select" data-def="">
						</select>
					</div>
				</div>
				<div class="col-sm-12 mb15">
					<label class="col-sm-2 control-label" >结果同步缓存</label>
					<div class="col-sm-2 form-control-static" id="div_radio_enabled">
						<input type="radio" onclick="changeEnabled('1')" name = "enabled" value="1"/>是
						<input type="radio" onclick="changeEnabled('0')" checked="checked" name = "enabled" value="0"/>否

					</div>
					<div style="display: none" id="div_input_cache_key">
						<label class="col-sm-2 control-label" >缓存KEY</label>
						<div class="col-sm-6 form-group">
							<input  type="text" name = "sysParamManager.cacheKey" data-name = "sysParamManager.cacheKey" class="form-control clean"  placeholder="请输入字母、数字或下划线"/>
						</div>
					</div>

				</div>
				<div class="col-sm-12 mb15">

					<label class="col-sm-2 control-label" >需要判断唯一性的字段</label>
					<div class="col-sm-6 form-group">
						<input  type="text" name = "sysParamManager.checkColumn" data-name = "sysParamManager.checkColumn" class="form-control clean"  placeholder="请输入字母、数字或下划线"/>
					</div>
				</div>
			</div>
		</div>
	</div>
	<div class="box-footer">
		<button type="button" class="btn btn-success pull-left" onclick="parent.preMonacoCallBack();">取消</button>
		<button type="button" class="btn btn-danger pull-right" onclick="save('submitForm');">提 交</button>
	</div>
</form>
<script>
    /** 统一请求地址 **/
    var common_list_url = "${ctx}/trans/list/";
    var common_info_url = "${ctx}/trans/info/";
    var common_submit_url = "${ctx}/trans/submit/";

    var index_load = layer.load(1, {shade: false});
    var dictListMap = DictUtil.initDictAndDymic();

    var clickMenu = "sysParamManager-list";
    var defSysEname = strUtil.doNull("${param.sysEname}","");
    var thisObjNameAll="";

    var editor,editor2;
    var  headerStrs = "",headerStrs2="";


    var id="${param.id}"
    if(!strUtil.isNull(id)){
        toEditInfo(id,"edit");
    }else{
        toEditInfo("","view");
	}
    $(function () {
        $("#submitForm_modelTypes").bind("input propertychange", function() {
            loadResultName();
        });
//        $("#searchForm_sysName").val(defSysEname);
//        window.parent.getTableData();
        //2、控制是否启用token
        //setToken();
//        $("#submitForm_sysName").val(defSysEname);

    });
	function changeEnabled(val) {
		if("1"==val){
			$("#div_input_cache_key").css("display","block");
		}else{
            $("#div_input_cache_key").css("display","none");
            $("#div_input_cache_key").find("input[name='sysParamManager.cacheKey']").val("");
            mytools.cleanValidate("#submitForm");//清除校验
		}
	}
    function toEditInfo(id,type){
        if("view"==type){
            require.config({ paths: { 'vs': '${ctx}/common/plateform/plugins/monaco-editor/min/vs' }});
            require(['vs/editor/editor.main'], function() {
                editor = monaco.editor.create(document.getElementById("relation_editor"),{
                    value: [
                        "/**{配置方法：如i_tDemoTest,s_tDemoShow，那么tDemoShow.属性名=[tDemoTest.属性名]，注意实体的顺序！}**/\n"
                    ].join('\n'),
                    theme:'vs-dark',
                    lineNumbers:'off',
                    minimap:{enabled:false},
                    wordWrap:'on',
                    language: 'java'
                });

                editor2 = monaco.editor.create(document.getElementById("resultColumn_editor"),{
                    value: [
                        "/**{配置方法:实体.属性名}**/\n"
                    ].join('\n'),
                    theme:'vs-dark',
                    lineNumbers:'off',
                    minimap:{enabled:false},
                    wordWrap:'on',
                    language: 'java'
                });
                layer.close(index_load);

            });
            headerStrs = "";
		}
		if("edit"==type){
            layer.close(index_load);
			index_load=layer.msg("正在加载数据。。。");
			var paramLoadData = {"sysParamManager.w_infoId":id, "pageName": "sys-param-manager","formName": "searchForm"};
			$.ajax({
                type:'get',
                url:common_info_url,
                data: paramLoadData,
                async:false,
                dataType:"json",
                success: function(myData){
                    // console.log("sysParamManager",myData);
                    showData(type,myData);
                    var relationValue=myData.sysParamManager.relation;
                    var resultColumnValue=myData.sysParamManager.resultColumn;
                    if(strUtil.isNull(relationValue)){
                        relationValue=headerStrs;
                    }else{
                        relationValue = headerStrs+relationValue;
                    }
                    if(strUtil.isNull(resultColumnValue)){
                        resultColumnValue=headerStrs;
                    }else{
                        resultColumnValue =headerStrs+resultColumnValue;
                    }
                    headerStrs ="";
                    require.config({ paths: { 'vs': '${ctx}/common/plateform/plugins/monaco-editor/min/vs' }});
                    require.config({
                        'vs/nls' : {
                            availableLanguages: {
                                '*': 'de'
                            }
                        }
                    });
                    require(['vs/editor/editor.main'], function() {
                        editor = monaco.editor.create(document.getElementById("relation_editor"),{
                            value: [
                                relationValue
                            ].join('\n'),
                            theme:'vs-dark',
                            lineNumbers:'off',
                            minimap:{enabled:false},
                            wordWrap:'on',
                            language: 'java'
                        });

                        editor2 = monaco.editor.create(document.getElementById("resultColumn_editor"),{
                            value: [
                                resultColumnValue
                            ].join('\n'),
                            theme:'vs-dark',
                            lineNumbers:'off',
                            minimap:{enabled:false},
                            wordWrap:'on',
                            language: 'java'
                        });

                        layer.close(index_load);
                    });

                }
            });
        }


    }


    //反显数据
    function showData(type,myData){
        //console.log(myData);
        if("view"==type){
            FormUtil.loadView("sysParamManager", myData);
            $("#my_modal_view").modal("show");

        }else if("edit"==type){
            var objData = myData.sysParamManager;
            $("#submitForm_rulesName").attr("name","sysParamManager.s_rulesName");
            //FormUtil.fillData("#submitForm", myData,"id");
            $("#submitForm_modelTypes").val(objData.modelTypes);

            var cacheKey = objData.cacheKey;
            if(cacheKey!=""&&cacheKey!=null&&cacheKey!=undefined){
                $("#div_input_cache_key").css("display","block");
                $("#div_radio_enabled").find("input[value='1']").attr("checked","checked");

			}
			var modelTypes=objData.modelTypes;
            var modelTypeArray = modelTypes.split(",");
			for(x in modelTypeArray){
				var objName = modelTypeArray[x];
				objName = objName.split("_")[1];
                var sortCode = objName.replace(objName.match(/[A-Z\s]+/g)[0],'_'+objName.match(/[A-Z\s]+/g)[0].toLowerCase());
                sortCode = strUtil.HumpToUnderline(sortCode.split("_")[1]);
                var result = toCache('',sortCode,defSysEname);
				if(!strUtil.isNull(result)){
                    if(strUtil.isNull(headerStrs)){
                        headerStrs = objName+":"+result.split(";")[1];
                    }else{
                        headerStrs = headerStrs+"\n"+objName+":"+result.split(";")[1];
                    }
				}

			}
            headerStrs="/**{配置方法:实体.属性名}\n{"+headerStrs+"}**/\n";

            FormUtil.loadView("sysParamManager", objData);
            loadResultName();
            DictUtil.checkSelectDict("#resultName",objData.resultName);


            $("#relation").attr("disabled",true);
            $("#relation").hide();
            $("#s_relation").show();
            $("#s_relation").attr("disabled",false);

            $("#resultColumn").attr("disabled",true);
            $("#resultColumn").hide();
            $("#s_resultColumn").show();
            $("#s_resultColumn").attr("disabled",false);


            $("#rulesName").attr("disabled",true);
            $("#rulesName").hide();
            $("#s_rulesName").show();
            $("#s_rulesName").attr("disabled",false);

            $("#evelName").val(objData.evelName);
            $("#submitForm").find("input[name='formName']").val("editForm");
            $("#w_infoId").val(objData.infoId);
        }
    }

    /**
     * 表单数据提交
     * @param formId
     */
    function save(formId){
        setValidate("#"+formId);//定义add表单验证属性
        if(strUtil.isNull($("#submitForm_modelTypes").val())){
            layer.alert("请先选择接口类型！");
            return;
        }
        var validate = $('#' + formId).data('bootstrapValidator').validate();
        if (!validate.isValid()) { //如果校验不通过就返回
            return;
        }
        var index_submit = layer.confirm('您确定要提交信息吗？', {btn: ['Yes','No'],closeBtn: 0,offset: '220px'}
            , function(){
				var relationContent = editor.getValue();
				var resultColumnContent = editor2.getValue();

                relationContent = relationContent.split("**/")[1];
                if(!strUtil.isNull(relationContent)){
                    relationContent = relationContent.trim();
                }
                resultColumnContent=resultColumnContent.split("**/")[1];
                if(!strUtil.isNull(resultColumnContent)){
                    resultColumnContent = resultColumnContent.trim();
				}


                $("#s_relation").val(relationContent);
                $("#relation").val(relationContent);
                $("#s_resultColumn").val(resultColumnContent);
                $("#resultColumn").val(resultColumnContent);
                layer.close(index_submit);
                $.ajax({
                    type:"post",
                    url:common_submit_url,
                    data:$("#"+formId).serialize(),
                    dataType:"json",
                    success: function(myData){
                        //console.log(myData);
                        if(myData.flag=="T"){
                            layer.alert("数据保存成功");
                            $("#my_modal").modal("hide");
                        }else{
                            layer.alert(myData.msg);
                        }
                        parent.preMonacoCallBack();
                    }
                });
            });
    }



    function loadResultName(){
        var modelTypes = $("#submitForm_modelTypes").val();
        if(modelTypes.indexOf("s_")>=0){
            if(modelTypes.indexOf(",")>=0){
                $("#resultName").html("<option value='T'>实体.属性名</option>");
            }else{
                $("#resultName").html("<option value='T'>实体.属性名</option><option value='F'>属性名</option>");
            }
            $(".resultName").show();
        }else{
            $(".resultName").hide();
        }

    }


    var loginWin=null;
    //选择数据表对象
    function showObjNameTable(){
        loginWin = layer.open({
            type: 2,
            title:"选择接口类型",
            shadeClose: false,
            shade: 0.6,
            area: ['86%', '86%'],
            offset: '20px',
            content: "${page_admin}/project/objName-table-pop-ius?objNameStr="+strUtil.doNull(thisObjNameAll,"")+"&sysEname="+defSysEname //iframe的url
        });
    }
    var tableObjNameMap = {};
    function preObjTableCallBack(objMap){
        // console.log(objMap);
        tableObjNameMap = objMap;
        layer.close(loginWin);
        var len  = Object.keys(tableObjNameMap).length;
        var modelTypsStrs = "",formNameStrs = "",formNameBatchStrs = "",pageNameStrs = "",sortCodeStrs="";
        var objName="";
        for(var key in tableObjNameMap){
            var obj = tableObjNameMap[key];
            modelTypsStrs+=obj.tableObjName+",";
            pageNameStrs=obj.tableName;//以最后选择项为准
            formNameStrs=obj.formName;//以最后选择项为准
            objName = obj.tableObjName;
            if(sortCodeStrs.indexOf(","+obj.sortCode)==-1){
                var result = toCache('',obj.sortCode,defSysEname);
                if(!strUtil.isNull(result)){
                    if(strUtil.isNull(headerStrs)){
                        headerStrs = objName.split("_")[1]+":"+result.split(";")[1];
                        headerStrs2 = objName.split("_")[1]+":"+result.split(";")[1];
                    }else{
                        headerStrs = headerStrs+"\n"+objName.split("_")[1]+":"+result.split(";")[1];
                        headerStrs2 = headerStrs2+"\n"+objName.split("_")[1]+":"+result.split(";")[1];
                    }
				}
                sortCodeStrs=sortCodeStrs+","+obj.sortCode;
            }
        }
        headerStrs="/**{配置方法：如i_tDemoTest,s_tDemoShow，那么tDemoShow.属性名=[tDemoTest.属性名]，注意实体的顺序！}\n{"+headerStrs+"}**/\n"
        editor.setValue(headerStrs);
        headerStrs2="/**{配置方法:实体.属性名}\n{"+headerStrs2+"**/\n";
        editor2.setValue(headerStrs2);
        headerStrs="",headerStrs2="";//滞空，防止下次带去上次的数据
        if(!strUtil.isNull(modelTypsStrs)){
            modelTypsStrs=modelTypsStrs.substring(0,modelTypsStrs.length-1);
        }
//    if(!strUtil.isNull(tableNameStr)){
//        tableNameStr=tableNameStr.substring(0,tableNameStr.length-1);
//    }
        $("#submitForm_modelTypes").val(modelTypsStrs);


        if(strUtil.isNull($("#formName").val())){
            $("#formName").val(formNameStrs);
        }
        if(strUtil.isNull($("#pageName").val())){
            pageNameStrs+="-"+formNameStrs.replace(/Form/g, "");
            if(len>1){
                pageNameStrs+=len;
            }
            pageNameStrs=pageNameStrs.replace(/_/g, "-");
            $("#pageName").val(pageNameStrs.toLowerCase());
        }

        loadResultName();


    }




    //1.定义校验规则-定义
    function setValidate(id) {
        $(id).each(function () {
            $(this).bootstrapValidator({
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                }, /** 以下需要结合实际业务清空补充个表单元素的验证规则 **/
                fields: {
                    /** 可自定义新增验证规则**/
                     "sysParamManager.cacheKey":{
									validators: {
										regexp: {
											regexp: /^[_a-zA-Z0-9]+$/,
											message: '只能是字母、数字或_'
										},
                                        notEmpty: {
                                            message: '不能为空！'
            							},
									}
					},
                    "sysParamManager.pageName":{
                        validators: {
                            notEmpty: {
                                message: '不能为空！'
                            },
                        }
                    },
                    "sysParamManager.formName":{
                        validators: {
                            notEmpty: {
                                message: '不能为空！'
                            },
                        }
                    }

                }
            });
        });
    }

    function toCache(spaceName, sortCode, sysName) {
        var cachekey = sortCode + "_" + sysName + "_tableAttr";
        var result = "";
        $.ajax({
            type: 'get',
            async:false,
			url: common_cache_url+"view",
			data:{"cacheSpaceName":spaceName,"cachekey":cachekey},
            // url: common_cache_url + '/sendPage/viewCache?spaeName=' + spaceName + "&code=" + cachekey,
            dataType: 'json',
            success: function (myData) {
                console.log("viewCache data",myData);
                result =  myData.msg;
            }
        });
        return result;
    }


</script>